import Mock from 'mockjs'

Mock.Random.extend({
  mystore(){
    return this.pick([
      '宠物店',
      '美容店',
      '小吃店',
      '数码店',
      '快餐店'
    ])
  }
})
// 模拟用户数据
const users = Mock.mock({
  'users|5': [
    {
      'id|+1': 1, // 自增ID
      'name': '@cname', // 随机中文名字
      "date":'@date',
      "city":'@county(true)',
      "dian":'@mystore',
      "dingDan|18":/\d/,
      "title":"@ctitle(20)"
    },
  ],
})
// 模拟接口
// 获取数据
Mock.mock('/api/users', 'get', {
  code: 200,
  message: 'success',
  data: users.users,
})

// 添加数据
Mock.mock("/api/users", 'post', (data) => {
  const {name,city,date,dian,title} = JSON.parse(data.body)
  const newUser = {
    id: Mock.Random.integer(1000, 9999), // 随机生成一个 ID
    name,
    city,
    date,
    dian,
    title
  }
  users.users.push(newUser)
  return {
    code: 200,
    message: '用户添加成功'
  }
})

//更新数据
Mock.mock(RegExp('/api/users'), 'patch', (req) => {
  const id = req.url.split('/').at(-1)
  const userIndex = users.users.findIndex((u) => u.id == id)
  if (userIndex !== -1) {
    const {name,city,date,dian,title} = JSON.parse(req.body)
    users.users[userIndex] = { ...users.users[userIndex], name,city,date,dian,title }
    return {
      code: 200,
      message: '更新成功'
    };
  } else {
    return {
      code: 404,
      message: '更新失败',
    }
  }
})


// 删除数据
Mock.mock(RegExp('/api/users'), 'delete', ({url}) => {
  const id = url.split('/').at(-1)
  const userIndex = users.users.findIndex((u) => u.id == id)
  if (userIndex !== -1) {
    users.users.splice(userIndex, 1)
    return {
      code: 200,
      message: '删除成功',
    }
  } else {
    return {
      code: 404,
      message: '删除失败',
    }
  }
})


export default Mock